package com.coszero.common.base.mvp;

import android.util.Log;

import com.coszero.utils.utils.LogX;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import org.json.JSONObject;

import java.lang.ref.WeakReference;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Desc：
 *
 * @author xmqian
 * Email:xmqian93@163.com
 * Date: 2021/8/20 17:01
 * @version 1
 */
public class BasePresenter<V extends BaseView> {

    private WeakReference<V> mWeakReference;
    private CompositeDisposable mCompositeDisposable;
    private V mView;

    public BasePresenter(V mView) {
        this.mView = mView;
        attach(mView);
    }

    public void attach(V v) {
        if (mWeakReference == null) {
            mWeakReference = new WeakReference<V>(v);
        }
        mView = v;
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
    }

    public <T> void addTask(Observable<T> observable, Consumer<T> consumer) {
        mCompositeDisposable.add(
                observable
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(consumer, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) {
                                try {
                                    getView().onNetworkError();
                                } catch (NullPointerException e) {
                                    Logger.i("####进度条为空");
                                }
                                Logger.t("发生异常").e(throwable.getMessage());
                                if (mWeakReference == null) return;
                                V v = mWeakReference.get();
                                if (v != null) {
                                    v.onNetworkError();
                                }
                            }
                        }));
    }


    public <T> void addTask(Observable<String> observable, final MyNetworkCallBack<T> myNetworkCallBack, final Class<T> clazz) {
        mCompositeDisposable.add(
                observable
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<String>() {
                            @Override
                            public void accept(String s) throws Exception {
                                LogX.i(s);

                                JSONObject resultObj = new JSONObject(s);
                                int resultNum = resultObj.optInt("result");
                                String msg = resultObj.optString("message");

//                                HttpRespond<T> httpRespond = new HttpRespond<>(resultNum, msg);
//
//                                int result = httpRespond.result;
//                                String message = httpRespond.message;
                                int result = resultNum;
                                String message = msg;
                                //token失效或未登录
                                if (result == -1) {
                                    myNetworkCallBack.onTokenInvalid(result, message);
                                    return;
                                }
                                //请求成功
                                if (result != 0) {
                                    String data = resultObj.optString("data");
                                    myNetworkCallBack.onSuccess(result, message, new Gson().fromJson(data, clazz));
                                } else {
                                    myNetworkCallBack.onFailed(result, message);
                                }
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) {
                                Log.e("http", "throwable: " + throwable.getMessage());
                                V v = mWeakReference.get();
                                if (v != null) {
                                    v.onNetworkError();
                                }
                            }
                        }));
    }


//    public <T> void addTask(Observable<String> observable, final MyNetworkCallBack<T> myNetworkCallBack) {
//        mCompositeDisposable.add(
//                observable
//                        .subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(new Consumer<String>() {
//                            @Override
//                            public void accept(String s) throws Exception {
//                                LogUtil.i(s);
//                                HttpRespond<T> httpRespond = new Gson().fromJson(s, new TypeToken<HttpRespond<T>>() {
//                                }.getType());
//                                int result = httpRespond.result;
//                                String message = httpRespond.message;
//
//                                //token失效或未登录
//                                if (result == -1) {
//                                    myNetworkCallBack.onTokenInvalid(result, message);
//                                    return;
//                                }
//                                //请求成功
//                                if (result != 0) {
//                                    myNetworkCallBack.onSuccess(result, message, httpRespond.data);
//                                } else {
//                                    myNetworkCallBack.onFailed(result, message);
//                                }
//                            }
//                        }, new Consumer<Throwable>() {
//                            @Override
//                            public void accept(Throwable throwable) throws Exception {
//                                Log.e("http", "throwable: " + throwable.getMessage());
//                                V v = mWeakReference.get();
//                                if (v != null) {
//                                    v.onNetworkError();
//                                }
//                            }
//                        }));
//    }

    public void detach() {
        mWeakReference = null;
        if (!mCompositeDisposable.isDisposed()) {
            mCompositeDisposable.dispose();
            mCompositeDisposable = null;
        }
    }

    public V getView() {
        mView = mWeakReference.get();
        return mView;
    }

    /**
     * 自定义网络回调
     *
     * @param <T>
     */
    public interface MyNetworkCallBack<T> {
        void onTokenInvalid(int result, String message);

        void onSuccess(int result, String message, T data);

        void onFailed(int result, String message);
    }

}
